package elicecn.web.struts2ext.dao;

import java.lang.reflect.Method;

import elicecn.web.struts2ext.model.BaseModel;

public final class IBatisDaoUtils {
	private IBatisDaoUtils() {
	}

	// 主键字段
	protected static String getPKName(BaseModel o) {
		Entity entity = o.getClass().getAnnotation(Entity.class);
		if (entity == null || entity.id() == null || entity.id().length() == 0) {
			return null;
		}
		return entity.id();
	}

	// 主键字段值
	public static Object getPKValue(BaseModel o) {
		String fieldName = getPKName(o);
		if (fieldName == null) {
			return null;
		}
		String getterMethod = "get" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
		try {
			Method getMethod = o.getClass().getMethod(getterMethod,
					(Class[]) null);
			return getMethod.invoke(o, (Object[]) null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	@SuppressWarnings("unchecked")
	protected static void setPrimaryKey(BaseModel o, Object value) {
		String fieldName = getPKName(o);
		try {
			Entity entity = o.getClass().getAnnotation(Entity.class);
			Class clazz = o.getClass().getDeclaredField(entity.id()).getType();

			String setMethodName = "set"
					+ fieldName.substring(0, 1).toUpperCase()
					+ fieldName.substring(1);

			Method setMethod = o.getClass().getMethod(setMethodName, clazz);
			if (value != null) {
				setMethod.invoke(o, value);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	public static String getObjectQuery(String className) {
		return "get" + className;
	}

	public static String getInsertQuery(String className) {
		return "add" + className;
	}

	public static String getUpdateQuery(String className) {
		return "update" + className;
	}

	public static String getUpdateSelectiveQuery(String className) {
		return "update" + className + "Selective";
	}

	public static String getRemoveQuery(String className) {
		return "remove" + className;
	}

	protected static String getCountQuery(String queryName) {
		return "count" + queryName.substring(0, 1).toUpperCase()
				+ queryName.substring(1);
	}

	protected static String getPaginationQuery(String className) {
		return "find" + className + "ListByPg";
	}
}
